//
//  LCProductDLVC.m
//  stone-story
//
//  Created by dodo liu on 12-9-25.
//  Copyright (c) 2012年 liu dodo. All rights reserved.
//

#import "LCProductDLVC.h"

@interface LCProductDLVC ()

@end

@implementation LCProductDLVC
@synthesize _delegate;
@synthesize finishDLProductIDArray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if(finishDLProductIDArray==nil)
        finishDLProductIDArray=[[NSMutableArray alloc]init];
    
    [self addRightButton];
    indexcount=0;
    [self requestSend];
    [self initpop];
    //[self showpop];
	// Do any additional setup after loading the view.
}
- (void)viewDidAppear:(BOOL)animated
{
    //if(!haveConnect)
    //{
    [LCtableView reloadData];
   // }
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return YES;
}

#pragma mark 数据请求
- (void)requestSend
{
    [self HUD_Create:self.view];
    [self HUD_Show];
     self.rootNodeName=@"product";   
    [self request_Send:WS_PRODUCTINFO withPostArg:nil];
        
}

//调用父类请求[成功]时的方法
- (void)getResultArraySuccess //请求回来并解释好的数据都放在[resultArray]这个数组中,直接引用
{
    [self HUD_Hide];
    [self tableView_init];
    haveConnect=YES;
    NSLog(@"[result count is:= %d]",resultArray.count);
    
}
//调用父类请求[失败]时的方法
- (void)requestError
{
    NSLog(@"发送请求失败");
    [self HUD_Hide];
}

#pragma mark 数据表格
- (void)tableView_init 
{
    CGRect tableFrame=CGRectMake(20,0,984,704); //矩形结构
    LCtableView=[[UITableView alloc]initWithFrame:tableFrame]; //分配内存，设置样式
    [LCtableView setDelegate:self]; //设置代理
    [LCtableView setDataSource:self]; //设置数据源
    [LCtableView setBackgroundColor:[UIColor clearColor]];
    [LCtableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [LCtableView setAllowsSelection:NO];
    [self.view addSubview:LCtableView]; //添加到父视图
    
}

//返回有多少个Sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}
//返回行数
- (NSInteger)tableView:(UITableView *)tableView  numberOfRowsInSection:(NSInteger)section { 
    return resultArray.count/5+1; 
    
}
//每个section的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return @"";
}

//指定行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 240.8;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    
    static NSString *TableSampleIdentifier = @"TableSampleIdentifier"; 
    
    UITableViewCell *cell = [LCtableView dequeueReusableCellWithIdentifier: 
                             TableSampleIdentifier]; 
    
    if (cell == nil) { 
        cell = [[UITableViewCell alloc] 
                initWithStyle:UITableViewCellStyleSubtitle 
                reuseIdentifier:TableSampleIdentifier]; 
    } 
    else {
        //重用CELL时候清空 SUBviews
        for(UIView *view in [cell.contentView subviews])
        {
            [view removeFromSuperview];
        }
    }
    
    cell.contentView.backgroundColor=[UIColor clearColor];
    NSMutableDictionary *nd;
    //创建按钮
    int item_one=[indexPath row]*5;
    int item_tow=item_one+1;
    int item_three=item_one+2;
    int item_four=item_one+3;
     int item_five=item_one+4;
    if(item_one<[resultArray count])
    {
        nd=[resultArray objectAtIndex:item_one];
        LCProductItem *itemOne=[[LCProductItem alloc]initWithFrame:CGRectMake(150*0+1*40.8,20.4,150,200) productLogoString:[nd valueForKey:@"product_logo"] productName:[nd valueForKey:@"product_name"] index:item_one];
        itemOne.delegate=self;
        [cell.contentView addSubview:itemOne];
        if([finishDLProductIDArray containsObject:[nd valueForKey:@"product_id"]])
        {
             [itemOne setActionBtnState:2];   
        }
        else if([downingProductIDArray containsObject:[nd valueForKey:@"product_id"]]){
            [itemOne setActionBtnState:1];
        }
        else 
        {
             [itemOne setActionBtnState:0];
        }
       
        indexcount++;
        
        [itemOne setTag:20000+item_one];
       
    }
     if(item_tow<[resultArray count])
    {
        nd=[resultArray objectAtIndex:item_tow];
        LCProductItem *itemTow=[[LCProductItem alloc]initWithFrame:CGRectMake(150*1+2*40.8, 20.4, 150, 200) productLogoString:[nd valueForKey:@"product_logo"] productName:[nd valueForKey:@"product_name"] index:item_tow];
        itemTow.delegate=self;
        
        [cell.contentView addSubview:itemTow];
        [itemTow setActionBtnState:0];
        
        if([finishDLProductIDArray containsObject:[nd valueForKey:@"product_id"]])
        {
            [itemTow setActionBtnState:2];   
        }
        else if([downingProductIDArray containsObject:[nd valueForKey:@"product_id"]]){
            [itemTow setActionBtnState:1];
        }
        else 
        {
            [itemTow setActionBtnState:0];
        }
        indexcount++;
        
        [itemTow setTag:20000+item_tow];
    }
    
     if(item_three<[resultArray count])
    {   
      
        
        nd=[resultArray objectAtIndex:item_three];
        LCProductItem *itemThree=[[LCProductItem alloc]initWithFrame:CGRectMake(150*2+3*40.8, 20.4, 150, 200) productLogoString:[nd valueForKey:@"product_logo"] productName:[nd valueForKey:@"product_name"] index:item_three];
        itemThree.delegate=self;
        [cell.contentView addSubview:itemThree];
         [itemThree setActionBtnState:0];
        if([finishDLProductIDArray containsObject:[nd valueForKey:@"product_id"]])
        {
            [itemThree setActionBtnState:2];   
        }
        else if([downingProductIDArray containsObject:[nd valueForKey:@"product_id"]]){
            [itemThree setActionBtnState:1];
        }
        else 
        {
            [itemThree setActionBtnState:0];
        }
        
        indexcount++;
        
        [itemThree setTag:20000+item_three];
    }
    
    if(item_four<[resultArray count])
    {
        nd=[resultArray objectAtIndex:item_four];
        LCProductItem *itemFour=[[LCProductItem alloc]initWithFrame:CGRectMake(150*3+4*40.8, 20.4, 150, 200) productLogoString:[nd valueForKey:@"product_logo"] productName:[nd valueForKey:@"product_name"] index:item_four];
        itemFour.delegate=self;
        [cell.contentView addSubview:itemFour];
        [itemFour setActionBtnState:0];
        
        if([finishDLProductIDArray containsObject:[nd valueForKey:@"product_id"]])
        {
            [itemFour setActionBtnState:2];   
        }
        else if([downingProductIDArray containsObject:[nd valueForKey:@"product_id"]]){
            [itemFour setActionBtnState:1];
        }
        else 
        {
            [itemFour setActionBtnState:0];
        }
        indexcount++;
        
        [itemFour setTag:20000+item_four];
    }
    
    if(item_five<[resultArray count])
    {
        nd=[resultArray objectAtIndex:item_five];
        LCProductItem *itemFive=[[LCProductItem alloc]initWithFrame:CGRectMake(150*4+5*40.8, 20.4, 150, 200) productLogoString:[nd valueForKey:@"product_logo"] productName:[nd valueForKey:@"product_name"] index:item_five];
        itemFive.delegate=self;
        [cell.contentView addSubview:itemFive];
        [itemFive setActionBtnState:0];
        
        if([finishDLProductIDArray containsObject:[nd valueForKey:@"product_id"]])
        {
            [itemFive setActionBtnState:2];   
        }
        else if([downingProductIDArray containsObject:[nd valueForKey:@"product_id"]]){
            [itemFive setActionBtnState:1];
        }
        else 
        {
            [itemFive setActionBtnState:0];
        }
        indexcount++;
        
        [itemFive setTag:20000+item_five];
    }

    return cell; 
}
//点击行事件 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    
}

- (void)itemClick:(id)sender :(int)index{
    NSLog(@"%d",index);
    LCProductItem *item=(LCProductItem*)[self.view viewWithTag:index+3000];
    [item setActionBtnState:1];
    NSMutableDictionary *nd=[resultArray objectAtIndex:index];
    
    UIAlertView* av = [[UIAlertView alloc]initWithTitle:nil 
													   message:[NSString stringWithFormat:@"是否下载产品：%@ ?",[nd valueForKey:@"product_name"]]
													  delegate:self
											 cancelButtonTitle:@"取消"
                                    otherButtonTitles:@"下载",nil];
    
    [av setTag:10000+index];
	[av show];
    
    
    
   /* 
    NSMutableDictionary *nd=[resultArray objectAtIndex:index];
    if(!pop_PDLM_VC)
        pop_PDLM_VC=[[LCProductDLMgr alloc] init];
    
    UIImageView *iv=(UIImageView*)[self.view viewWithTag:5000+index];
    NSLog(@"nd dec:%@",[nd description]);
    NSLog(@"image width:%f",iv.image.size.width);
    [pop_PDLM_VC startDownLoad:nd productImage:iv.image];
    */
}

- (void) alertView:(UIAlertView *)alertview clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%d",buttonIndex);
    int index;
    index=[alertview tag]-10000;
    if(buttonIndex==1)
    { 
         NSMutableDictionary *nd=[resultArray objectAtIndex:index];
        if(!pop_PDLM_VC)
            pop_PDLM_VC=[[LCProductDLMgr alloc] init];
        
        UIImageView *iv=(UIImageView*)[self.view viewWithTag:5000+index];
        NSLog(@"nd dec:%@",[nd description]);
        NSLog(@"image width:%f",iv.image.size.width);
        [pop_PDLM_VC startDownLoad:nd productImage:iv.image];
        
        if(downingProductIDArray==nil)
            downingProductIDArray=[[NSMutableArray alloc]init];
        [downingProductIDArray addObject:[nd valueForKey:@"product_id"]];
        
        LCProductItem *pi=(LCProductItem*)[self.view viewWithTag:[self getIndexByProductID:[nd valueForKey:@"product_id"]]+20000];
        [pi setActionBtnState:1];

    }
}

#pragma mark - 右边按钮
- (void)addRightButton
{
  
    
    //增加一个详细按钮
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"查看下载"  style:UIBarButtonItemStylePlain target:self action:@selector(clickRightButton)];
    
    [self.navigationItem  setRightBarButtonItem:rightBtn];
    
}



-(void)clickRightButton
{
    NSLog(@"点击了查看下载");
    [self showpop];
    //全局变量isLogin标识是否登录
  

    
}

-(void)finishDownLoad:(NSString *)productID
{
    NSLog(@"产品ID为%@已经下载完毕",productID);
    LCProductItem *pi=(LCProductItem*)[self.view viewWithTag:[self getIndexByProductID:productID]+20000];
    [finishDLProductIDArray addObject:productID];
    [pi setActionBtnState:2];
    [_delegate refreshProductList];
    [downingProductIDArray removeObjectIdenticalTo:productID];
}

-(int)getIndexByProductID:(NSString *)productID
{
    int pa_index;
    for(int i=0;i<resultArray.count;i++)
    {
        NSMutableDictionary *nd=[resultArray objectAtIndex:i];
        if([productID isEqualToString:[nd valueForKey:@"product_id"]])
        {
            pa_index=i;
            break;
        }
    }
    return pa_index;
}

#pragma mark -popVC

-(void)initpop
{
    if(pop_PDLM_VC==nil)
        pop_PDLM_VC=[[LCProductDLMgr alloc] init];
    [pop_PDLM_VC setMgr_delegate:self];
    if(!popover)
        popover = [[UIPopoverController alloc] initWithContentViewController:pop_PDLM_VC];
    [popover setDelegate:self];
    [popover setPopoverContentSize:CGSizeMake(300,620)];
    pop_PDLM_VC.contentSizeForViewInPopover=pop_PDLM_VC.view.bounds.size;  
}
-(void)showpop
{ 
 
    [popover presentPopoverFromRect:CGRectMake(1010, 0, 10, 10) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController*)popoverController{
   /*
    if (popover) {
       // [popover dismissPopoverAnimated:YES];
    
        // [popover release];
      //  popover=nil;
        if (pop_PDLM_VC != nil) {
            // [popoverContent release];
            //pop_PDLM_VC = nil;
        }
    }
    */
}
-(void)killPopoversOnSight {
    /*
    if (popover) {
        [popover dismissPopoverAnimated:NO];
    }
     */
}

@end
